#include "music.h"

#ifdef USE_SDL_MIXER

void FreeMusic(Mix_Music *&music)
{
    if(music)
    {
        Mix_FreeMusic(music);
        music = NULL;
    }
}

//ZMusic is a very simple class, each call basically wraps a self-explanatory function of SDL_Mixer
const int Music::LoopInfinite = -1;    //constant for infinite, as used by SDL_Mixer

Music::Music() : 
    rMusic(NULL)
{
}

Music::Music(std::string filename) : 
    rMusic(NULL)
{
    Open(filename);
}

Music::~Music()
{
    Release();
}

void Music::Open(std::string filename)
{
    Release();

    rMusic = Mix_LoadMUS(filename.c_str());

    if(!rMusic)
        ;
}

void Music::Release()
{
    Mix_HaltMusic();
    FreeMusic(rMusic);
}

void Music::Play(int loopNum, int fadeTime) const
{
    if(Mix_PlayingMusic())    //stop currently playing music
        Mix_HaltMusic();

    if(rMusic)
    {
        if(fadeTime)
            Mix_FadeInMusic(rMusic, loopNum, fadeTime);
        else
            Mix_PlayMusic(rMusic, loopNum);
    }
    else
        ;
}

void Music::Pause() const
{
    if(rMusic)
        Mix_PauseMusic();
    else
        ;
}

void Music::Unpause() const
{
    if(rMusic)
        Mix_ResumeMusic();
    else
        ;
}

void Music::Rewind() const
{
    if(rMusic)
        Mix_RewindMusic();
    else
        ;
}

void Music::Stop(int fadeTime) const
{
    if(rMusic)
    {
        if(fadeTime)
            Mix_FadeOutMusic(fadeTime);
        else
            Mix_HaltMusic();
    }
    else
        ;
}

void Music::SetVolume(int volume)
{
    if(rMusic)
        Mix_VolumeMusic(volume);
    else
        ;
}

bool Music::IsLoaded() const
{
    return rMusic != NULL;
}

bool Music::IsPlaying() const
{
    if(rMusic)
        return Mix_PlayingMusic() > 0;
    else
    {
        
        return false;
    }
}

bool Music::IsPaused() const
{
    if(rMusic)
        return Mix_PausedMusic() > 0;
    else
    {
        
        return false;
    }
}

int Music::Volume() const
{
    if(rMusic)
        return Mix_VolumeMusic(-1);
    else
    {       
        return false;
    }
}

#endif 